package com.wang.transfer.service.impl;

import com.wang.common.common.ErrorCode;
import com.wang.common.exception.BusinessException;
import com.wang.common.utils.FileUtil;
import com.wang.transfer.entity.TreeToJsonConfig;
import com.wang.transfer.service.TreeJsonService;
import com.wang.transfer.util.propertiesToJson.treeJson.TreeToJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * tree to json
 */
@Service("treeJsonService")
@Slf4j
public class TreeJsonServiceImpl implements TreeJsonService {

    @Resource
    private TreeToJson treeToJson;

    @Value("${prop.file.pat}")
    private String pat;

    @Value("${prop.file.read}")
    private String readFile;

    @Value("${prop.file.write}")
    private String writeFile;

    @Override
    public String proToJson(MultipartFile file, TreeToJsonConfig config) {

        log.info("=========================treeJsonService proToJson start:{}==========================", config);
        String oldName = file.getOriginalFilename();
        String newName = FileUtil.getFileName(".json");
        try {
            // 保存旧文件
            FileUtil.saveFile(file.getInputStream(), oldName, readFile);
            // 转换 并 保存文件
            treeToJson.setReadFilePath(readFile + oldName)
                    .setWriteFilePath(writeFile + newName)
                    .setSYMBOL(config.getSymbol())
                    .setINDENT(config.getIndent())
                    .execute();
        } catch (IOException e) {
            log.error("{} 转换失败：{}", oldName, e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "转换失败");
        }
        log.info("=========================treeJsonService proToJson end:{}==========================", pat + newName);
        return pat + newName;
    }

    @Override
    public List<String> proToJsons(List<MultipartFile> files, TreeToJsonConfig config) {

        List<String> sts = new ArrayList<>();
        for (MultipartFile file : files) {
            String s = proToJson(file, config);
            sts.add(s);
        }
        return sts;
    }
}
